package com.avocado.bt.impl.composite;

import com.avocado.bt.BTState;
import com.avocado.bt.IBTContext;
import com.avocado.bt.IBTNode;
import com.avocado.bt.abs.composite.CompositeNode;

import java.util.Iterator;

/**
 * 依次执行每个子节点直到其中一个执行成功或者返回Running状态
 *
 * @Author: zsh
 * @Date: 2023/10/16 17:14
 */
public class SelectorNode extends CompositeNode {

    public SelectorNode(String param) {
        super(param);
    }

    @Override
    public BTState doUpdate(IBTContext context) {
        Iterator<IBTNode> iterator = getChildNodes().iterator();
        while (iterator.hasNext()) {
            IBTNode childNode = iterator.next();
            if (BTState.Completed.equals(childNode.getState()) || BTState.Failure.equals(childNode.getState())) {
                continue;
            }
            BTState tick = childNode.tick();
            if (tick != BTState.Failure) {
                return tick;
            }
            if (!iterator.hasNext()) {
                return BTState.Failure;
            }
        }
        return BTState.Failure;
    }

}
